package com.cb.admin.controllers;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cb.admin.domain.RoleInfo;
import com.cb.admin.domain.UserInfo;
import com.cb.admin.domain.UserRoleRef;
import com.cb.admin.service.IRoleInfoService;
import com.cb.admin.service.IUserInfoService;
import com.cb.admin.service.IUserRoleRefService;
import com.cb.auth.RetryLimitHashedCredentialsMatcher;
import com.cb.constants.Constants;
import com.cb.constants.UserTypeEnum;
import com.cb.util.Base64;
import com.cb.util.JSONUtil;

@Controller
@RequestMapping("/userinfo")
public class UserController extends BaseController{

	private static Logger logger = Logger.getLogger(UserController.class.getName());
	
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private IRoleInfoService roleInfoService;
	@Autowired
	private IUserRoleRefService userRoleRefService;
	@Autowired
	private RetryLimitHashedCredentialsMatcher retryLimitHashedCredentialsMatcher;
	
	@RequiresRoles("admin")//访客模式
	@RequestMapping("show")
	public String show(Model model){
		return "user/userInfoList";
	}

	@RequiresRoles("admin")//访客模式
	@RequestMapping(path = "/getList", method = RequestMethod.POST)
	@ResponseBody
	public String getUserList(UserInfo userInfo) {
		//当前页  
        userInfo.setStart((userInfo.getPage()-1)*userInfo.getRows());
		userInfo.setLength(userInfo.getRows());
		
		JSONObject jo = new JSONObject();
		
		List<Map> objs = userInfoService.query(userInfo);
		
		int size = userInfoService.querySize(userInfo);
		jo.put("rows", objs);
		jo.put("total", size);
		return jo.toString();
	}
	
	@RequiresRoles("admin")//访客模式
	@RequestMapping("createPage")
	public String createPage(Model model){
		model.addAttribute("userTypelis",EnumSet.allOf(UserTypeEnum.class));
		return "user/userInfoDetail";
	}
	
	@RequiresRoles("admin")//访客模式
	@RequestMapping(path = "/create", method = RequestMethod.POST)
	@ResponseBody
	public String create(Model model,UserInfo userInfo,HttpServletRequest request,HttpSession session,
			@RequestParam("roleId") String roleId){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);

		int size = userInfoService.queryByAccount(userInfo.getAccount());
		
		if(size>0){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jo.put("code", Constants.returnObj.returnCode.code_1);
			return jo.toString();
		}
		
		try {
			String pwd = userInfo.getPwd();
			userInfo.setPwd(returnPwd(userInfo.getAccount(), userInfo.getPwd()));
			userInfo.setPhoto(Base64.getBase64(pwd));
			userInfo.setCreateUser(returnSessionObj(session).getAccount());
			userInfo.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
			userInfo.setUpdateUser(returnSessionObj(session).getAccount());
			int id = userInfoService.insert(userInfo);
			
			if(roleId!=null && !"".equals(roleId)){
				//角色ID
				for(String rid:roleId.split(",")){
					UserRoleRef obj = new UserRoleRef();
					obj.setUserId(id);
					obj.setRoleId(Integer.parseInt(rid));
					userRoleRefService.insert(obj);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			JSONUtil.returnFailReuslt(null);
		}
		
		return jo.toString();
	}
	
	@RequiresRoles("admin")//访客模式
	@RequestMapping("edit")
	public String edit(Model model,@RequestParam("id") int id){
		UserInfo obj = userInfoService.queryById(id);
		
		obj.setPwd(Base64.getFromBase64(obj.getPhoto()));
		
		List<UserRoleRef> userRoleRefs = userRoleRefService.queryId(id);
		
		String roleId = "";
	
		for(UserRoleRef urp:userRoleRefs){
			roleId+=urp.getRoleId()+",";
		}
		model.addAttribute("userTypelis",EnumSet.allOf(UserTypeEnum.class));
		model.addAttribute("roleId", roleId);
		model.addAttribute("userinfo", obj);
		return "user/userInfoEdit";
	}
	
	@RequiresRoles("admin")//访客模式
	@RequestMapping(path = "/update", method = RequestMethod.POST)
	@ResponseBody
	public String update(Model model,UserInfo userInfo,HttpServletRequest request,HttpSession session,
			@RequestParam("roleId") String roleId){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			String pwd = userInfo.getPwd();
			userInfo.setPwd(returnPwd(userInfo.getAccount(), userInfo.getPwd()));
			userInfo.setPhoto(Base64.getBase64(pwd));
			userInfo.setUpdateUser(returnSessionObj(session).getAccount());
			userInfoService.update(userInfo);
			
			if(roleId!=null && !"".equals(roleId)){
				//角色ID
				userRoleRefService.deleteById(userInfo.getId());
				for(String rid:roleId.split(",")){
					UserRoleRef obj = new UserRoleRef();
					obj.setUserId(userInfo.getId());
					obj.setRoleId(Integer.parseInt(rid));
					userRoleRefService.insert(obj);
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			JSONUtil.returnFailReuslt(null);
		}
		
		return jo.toString();
	}
	
	@RequiresRoles("admin")//访客模式
	@RequestMapping("deleteById")
	@ResponseBody
	public String deleteById(Model model,@RequestParam("Ids") String Ids){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			userInfoService.deleteById(Integer.parseInt(id));
		}
		
		return jo.toString();
	}
	
	@RequiresRoles("admin")//访客模式
	@RequestMapping("userRefRoleJson")
	@ResponseBody
	public String userRefRoleJson(@RequestParam("roleId") String roleId){
		JSONObject jo = new JSONObject();
		List<RoleInfo> roleInfos = roleInfoService.getListAll();
		List<Map> reps = new ArrayList<Map>();
		for(RoleInfo obj:roleInfos){
			Map rep = new HashMap();
			rep.put("id", obj.getId());
			rep.put("pId", 0);
			rep.put("name", obj.getName());
			rep.put("open", true);
			if(roleId!=null){
				rep.put("checked", (","+roleId).indexOf(","+obj.getId()+",")!=-1?true:false);
			}else{
				rep.put("checked", false);
			}
			
			reps.add(rep);
		}
		jo.put("reps", reps);
		return jo.toString();
	}
	
	/**
     * 解除admin 用户的限制登录 
     * 写死的 方便测试
     * @return
     */
    @RequestMapping("/unlockAccount")
    @ResponseBody
    public String unlockAccount(@RequestParam("userId") int userId){
    	JSONObject jo = new JSONObject();
    	jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		retryLimitHashedCredentialsMatcher.unlockAccount(userId);
        return jo.toString();
    }
	
	/**
	 * 盐值加密
	 * @param account
	 * @param pwd
	 * @return
	 */
	private String returnPwd(String account,String pwd){
		int hashIterations = 1024;//加密的次数
		ByteSource credentialsSalt = ByteSource.Util.bytes(account);
		Object credentials = pwd;//密码
		String hashAlgorithmName = "MD5";//加密方式
		Object simpleHash = new SimpleHash(hashAlgorithmName, credentials,
				credentialsSalt, hashIterations);
//		System.out.println("加密后的值----->" + simpleHash);
		return simpleHash.toString();
	}
}